package com.leo.ibatis.demo.web.controller;

import java.util.LinkedHashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.validation.BindException;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;

import com.leo.ibatis.demo.criteria.LineitemCriteria;
import com.leo.ibatis.demo.domain.Lineitem;
import com.leo.ibatis.demo.service.LineitemService;

public class LineitemFormController extends SimpleFormController {

	private LineitemService lineitemService;

	public void setLineitemService(LineitemService lineitemService) {
		this.lineitemService = lineitemService;
	}

	@Override
	@SuppressWarnings("unchecked")
	protected Map referenceData(HttpServletRequest request) throws Exception {
		String mode = ServletRequestUtils.getRequiredStringParameter(request, "mode");
		
		LineitemCriteria lineitemCriteria = new LineitemCriteria();
		ServletRequestDataBinder binder = createBinder(request, lineitemCriteria);
		binder.bind(request);
		
		Map map = new LinkedHashMap();
		map.put("mode",  mode);
		map.put("lineitemCriteria", lineitemCriteria);

		return map;
	}

	@Override
	protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) throws Exception {
	}

	@Override
	protected void onBind(HttpServletRequest request, Object command, BindException errors) throws Exception {
	}

	@Override
	protected void onBindAndValidate(HttpServletRequest request, Object command, BindException errors) throws Exception {
	}

	@Override
	protected Object formBackingObject(HttpServletRequest request) throws Exception {
		Lineitem lineitem = null;
		
		String mode = ServletRequestUtils.getRequiredStringParameter(request, "mode");

		if (mode.equals("write")) {
			lineitem = new Lineitem();
		}
		
		if (mode.equals("edit")) {
			int linenum = ServletRequestUtils.getRequiredIntParameter(request, "linenum");
			int orderid = ServletRequestUtils.getRequiredIntParameter(request, "orderid");

			lineitem = lineitemService.select(linenum, orderid);
		}

		return lineitem;
	}

	@Override
	protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object command, BindException errors) throws Exception {
		String mode = ServletRequestUtils.getRequiredStringParameter(request, "mode");
		
		Lineitem lineitem = (Lineitem) command;
		
		if (mode.equals("write")) {
			lineitemService.insert(lineitem);
		} else if (mode.equals("edit")) {
			lineitemService.update(lineitem);
		}

		return new ModelAndView(getSuccessView());
	}

}
